﻿(function (win) {
    var map,
        options,
        api = {},
        overlays = [],
        infoWindow,
        MinDrawArea = 100,/*多边形最小面积（平方米）*/
        drawingManager,
        styleOptions,
        infoWinDoms;
    var defaults = {
        infoWindowOption: {
            title: '设置'
        },
        mapDrawOption: {
            strokeColor: "red",    //边线颜色。
            fillColor: "red",      //填充颜色。当参数为空时，圆形将没有填充效果。
            strokeWeight: 3,       //边线的宽度，以像素为单位。
            strokeOpacity: 0.8,	   //边线透明度，取值范围0 - 1。
            fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
            strokeStyle: 'solid' //边线的样式，solid或dashed。
        },
        FromType: 0
    };

    function init(opt) {
        options = $.extend(true, {}, defaults, opt);
        styleOptions = options.mapDrawOption;
        var ids = opt.mapBelongs || [];
        map = new BMap.Map('map');
        map.centerAndZoom(options.MapCity, options.MapZoom);
        map.enableScrollWheelZoom();

        infoWinDoms = {
            dialog: $('#infoWindow'),
            mapBelongs: $('#mapBelongs'),
            btnSignMap: $('#btnSignMapBelong'),
            btnClearArea: $('#btnClearArea')
        };

        var idTextKv = {};
        $.each(ids, function (i, item) {
            var label = idTextKv[item.mapId] = item.label || item.text;
            var option = $('<option/>', {
                text: item.text,
                value: item.mapId
            }).data({
                label: label,
                location: item.center
            });
            infoWinDoms.mapBelongs.append(option);
        });
        opt.mapData && $.each(opt.mapData, function (i, item) {
            var mapId = item.mapId;
            var labelText = idTextKv[mapId];
            $.each(item.datas, function (j, item1) {
                var paths = $.map(item1.paths, function (p, z) {
                    return new BMap.Point(p.lng, p.lat);
                });
                var center = item1.center;
                var option = $.extend(true, {}, styleOptions, item1.opts);
                var polygon = new BMap.Polygon(paths, option);
                var point = new BMap.Point(center.lng, center.lat);
                var marker = new BMap.Marker(point);
                marker.enableDragging();
                map.addOverlay(polygon);
                map.addOverlay(marker);
                var label = new BMap.Label(labelText, {
                    position: point,
                    offset: new BMap.Size(-5, -19)
                });
                marker.setLabel(label);
                marker.data_label = label;
                polygon.data_marker = marker;
                polygon.data_mapId = mapId;
                overlays.push(polygon);
                bindEvent(polygon);
            });
        });

        infoWinDoms.dialog.on('init', function () {
            var overlay = infoWinDoms.dialog.data('overlay');
            infoWinDoms.mapBelongs.val(overlay.data_mapId || '');
            if (overlay) {
                infoWinDoms.dialog.find('.colorShow').each(function () {
                    var self = $(this), name = self.attr('data-name'), bgColor;
                    switch (name) {
                        case 'strokeColor':
                            bgColor = overlay.getStrokeColor();
                            break;
                        case 'fillColor':
                            bgColor = overlay.getFillColor();
                            break;
                        default:
                            alert('未知：' + name);
                            break;
                    }
                    bgColor && self.css('backgroundColor', bgColor);
                });
            }
        });
        infoWinDoms.btnSignMap.on('click', function () {
            var overlay = infoWinDoms.dialog.data('overlay');
            if (overlay) {
                var opt = infoWinDoms.mapBelongs.find('option:selected');
                var loc = opt.data('location');
                var labelText = opt.data('label') || opt.text();
                if (loc) {
                    loc = new BMap.Point(loc.lng, loc.lat);
                } else {
                    var bound = overlay.getBounds();
                    var center = bound.getCenter();
                    loc = center;
                }
                var marker = overlay.data_marker;
                marker && map.removeOverlay(marker);

                marker = new BMap.Marker(loc);
                marker.enableDragging();
                map.addOverlay(marker);
                var label = new BMap.Label(labelText, {
                    position: loc,
                    offset: new BMap.Size(-5, -19)
                });
                marker.setLabel(label);
                marker.data_label = label;
                overlay.data_marker = marker;
                overlay.data_mapId = opt.val();
            }
            map.closeInfoWindow();

        });
        infoWinDoms.btnClearArea.on('click', function () {
            var overlay = infoWinDoms.dialog.data('overlay');
            if (overlay) {
                map.removeOverlay(overlay);
                var index = $.inArray(overlay, overlays);
                if (index != -1) {
                    var marker = overlay.data_marker;
                    marker && map.removeOverlay(marker);
                    overlays.splice(index, 1);
                }
            }
            map.closeInfoWindow();
        });
        infoWinDoms.dialog.find('.colorShow').colorpicker({
            success: function (obj, color) {
                obj.css('backgroundColor', color);
                var name = obj.attr('data-name');
                var overlay = infoWinDoms.dialog.data('overlay');
                if (overlay) {
                    switch (name) {
                        case 'strokeColor':
                            overlay.setStrokeColor(color);
                            break;
                        case 'fillColor':
                            overlay.setFillColor(color);
                            break;
                        default:
                            alert('未知：' + name);
                            break;
                    }
                }
            }
        });

        infoWindow = new BMap.InfoWindow(infoWinDoms.dialog.get(0), options.infoWindowOption);
        infoWindow.addEventListener('open', function () {
            infoWinDoms.dialog.triggerHandler('init');
        });

        drawingManager = new BMapLib.DrawingManager(map, {
            isOpen: false, //是否开启绘制模式
            enableDrawingTool: true, //是否显示工具栏
            drawingToolOptions: {
                anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
                offset: new BMap.Size(5, 5), //偏离值
                drawingModes: [
                    BMAP_DRAWING_POLYGON,
                    BMAP_DRAWING_RECTANGLE
                ]
            },
            polygonOptions: styleOptions, //多边形的样式
            rectangleOptions: styleOptions //矩形的样式
        });
        drawingManager.addEventListener('rectanglecomplete', function (overlay) {
            var ply = new BMap.Polygon(overlay.getPath());
            var area = BMapLib.GeoUtils.getPolygonArea(ply);
            if (area >= MinDrawArea) {
                bindEvent(overlay);
                drawingManager.close();
                return overlays.push(overlay);
            }
            map.removeOverlay(overlay);
        });
        drawingManager.addEventListener('polygoncomplete', function (overlay) {
            if (overlay.getPath().length >= 3) {
                var ply = new BMap.Polygon(overlay.getPath());
                var area = BMapLib.GeoUtils.getPolygonArea(ply);
                if (area >= MinDrawArea) {
                    drawingManager.close();
                    bindEvent(overlay);
                    return overlays.push(overlay);
                }
            } else {
                alert('最少三个点');
            }
            map.removeOverlay(overlay);
        });

        $('#topColorSet .colorShow').each(function () {
            var self = $(this), name = self.attr('data-name'), bgColor = styleOptions[name];
            bgColor && self.css('backgroundColor', bgColor);
        }).colorpicker({
            success: function (obj, color) {
                obj.css('backgroundColor', color);
                var name = obj.attr('data-name');
                var p = {};
                p[name] = color;
                $.extend(styleOptions, p);
            }
        });
    }

    /*给画的图形添加事件*/
    function bindEvent(overlay) {
        overlay.addEventListener('rightclick', function (ev) {
            infoWinDoms.dialog.data('overlay', overlay);
            map.openInfoWindow(infoWindow, ev.point);
        });
    }

    /*返回标注数据*/
    function getMapData() {
        var data = {};
        $.each(overlays, function (i, overlay) {
            var mapId = overlay.data_mapId;
            if (!mapId) {
                return;
            }
            var d = data[mapId] || (data[mapId] = []);
            var marker = overlay.data_marker;
            var paths = overlay.getPath(),
                opts = {},
                center = marker.getPosition();
            opts['fillColor'] = overlay.getFillColor();
            opts['strokeColor'] = overlay.getStrokeColor();
            d.push({
                paths: paths,
                center: center,
                opts: opts
            });
        });
        var arr = [];
        $.each(data, function (k, v) {
            arr.push({ mapId: k, datas: v });
        });
        return {mapData:arr};
    }

    api.init = init;
    api.getMapData = getMapData;

    api.btnSave = function () {
        var d = getMapData();
        if (d.mapData.length == 0) {
            return alert('请确认是否已标记！');
        }
        mapCommon.callback(options, d);
    };

    win.mapDrawArea = api;
})(window);